package com.example.service.impl;

import com.example.dto.dataresource.ConnectDto;
import com.example.entity.DataResource;
import com.example.exception.BizAssertUtils;
import com.example.mapper.DataResourceMapper;
import com.example.service.DataResourceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.HashMap;

/**
 * <p>
 * 数据库源表 服务实现类
 * </p>
 *
 * @author baomidou
 * @since 2023-02-28
 */
@Service
public class DataResourceServiceImpl extends ServiceImpl<DataResourceMapper, DataResource> implements DataResourceService {

    @Autowired
    private DataResourceMapper dataResourceMapper;
    @Override
    public HashMap<String,Object> modalConnMysql(ConnectDto sqlInfo) {
        return connectJdbc(sqlInfo);
    }

    @Override
    public HashMap<String,Object> tableConnMysql(Integer id) {
        DataResource dataResource = dataResourceMapper.selectById(id);
        BizAssertUtils.notNull(dataResource,"数据源不存在");
        ConnectDto addOrUpdateOrConnectDto = new ConnectDto();
        BeanUtils.copyProperties(dataResource,addOrUpdateOrConnectDto);
        return connectJdbc(addOrUpdateOrConnectDto);
    }


    private HashMap<String,Object> connectJdbc(ConnectDto sqlInfo) {
        HashMap<String, Object> map = new HashMap<>();
//        "com.mysql.cj.jdbc.Driver"
        try {
            Class.forName(sqlInfo.getDriverClassName());
            Connection connection = DriverManager.getConnection(sqlInfo.getUrl(), sqlInfo.getAccount(), sqlInfo.getPassword());
            connection.close();
            map.put("status",true);
            map.put("message","连接成功");
            return map;
        } catch (Exception e){
            System.out.println();
            map.put("status",false);
            map.put("message",e.getMessage());
            return map;
        }
    }
}
